package com.kalvan.core.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.RandomStringUtils;

import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.UUID;

/**
 * UUID工具类
 *
 * @author chenliang
 */
public class UuidUtil {
    private static final SimpleDateFormat TIMES_DF = new SimpleDateFormat("yyyyMMddHHmmssSSS");

    public UuidUtil() {

    }

    /**
     * 获得一个UUID
     *
     * @return String UUID
     */
    public static String uuid16() {
        return UUID.randomUUID().toString().replace("-", "").toLowerCase();
    }

    public static String uuid64() {
        UUID uuid = UUID.randomUUID();
        ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
        bb.putLong(uuid.getMostSignificantBits());
        bb.putLong(uuid.getLeastSignificantBits());
        return Base64.encodeBase64URLSafeString(bb.array());
    }

    /**
     * 获得指定数目的UUID
     *
     * @param number int 需要获得的UUID数量
     * @return String[] UUID数组
     */
    public static String[] getUUID(int number) {
        if (number < 1) {
            return null;
        }
        String[] ss = new String[number];
        for (int i = 0; i < number; i++) {
            ss[i] = uuid16();
        }
        return ss;
    }

    synchronized public static String time22() {
        StringBuilder sb = new StringBuilder();
        sb.append(TIMES_DF.format(System.currentTimeMillis()));
        sb.append(RandomStringUtils.randomNumeric(5));
        return sb.toString();
    }
}
